import org.molamil.acto.commands.CommandContext;
import org.molamil.acto.commands.factory.CommandFactory;
import org.molamil.acto.commands.factory.DependsError;
import org.molamil.acto.commands.factory.DependsNotFoundError;
import org.molamil.acto.core.Logger;
import org.molamil.commons.StringUtil;

/**
 * @author Jorge Hernandez
 */
class org.molamil.acto.commands.CommandsFactoryFinisher {
	
	
	// Constants
	
	public static var ERROR_DEPENDS_SELF:String = "ERROR: A command can not depend on itself (\"{command}\").";
	public static var ERROR_DEPENDS_DUPLICATE:String = "ERROR: Duplicate depends (\"{command}\").";
	public static var ERROR_DEPENDS_NOT_FOUND:String = "ERROR: A depended command could not be found (\"{command}\").";
	
	
	// Properties
	
	private static var log:Logger = Logger.getLogger("CommandsFactoryFinisher");
	
	
	// Functions
	
	public static function run(factory:CommandFactory):Void {
		log.debug("run()");
		runDepends(factory);
	}
	
	private static function runDepends(factory:CommandFactory):Void {
		var a:Array = factory.getCommands();
		for (var i:Number = 0; i < a.length; i++) {
			var context:CommandContext = a[i];
			if (context.depends != null) {
				var dependsHistory:Array = new Array();
				for (var j:Number = 0; j < context.depends.length; j++) {
					var name:String = context.depends[j];
					for (var k:Number = 0; k < dependsHistory.length; k++) {
						if (dependsHistory[k] == name) {
							var msg:String = StringUtil.replace(ERROR_DEPENDS_DUPLICATE, "{command}", name);
							throw new DependsError(msg);
						}
					}
					dependsHistory.push(name);
					var movie:CommandContext = factory.getCommand(name);
					if (movie == null) {
						var msg:String = StringUtil.replace(ERROR_DEPENDS_NOT_FOUND, "{command}", name);
						throw new DependsNotFoundError(msg);	
					}
					if (name == context.name) {
						var msg:String = StringUtil.replace(ERROR_DEPENDS_SELF, "{command}", name);
						throw new DependsError(msg);	
					}
				}
			}
		}
	}
	
	
}
